import Vue from 'vue'
import Router from 'vue-router'
import User from '@/components/User'
import Admin from '@/components/Admin'
import Login from '@/components/Login'
import AdminLogin from '@/components/AdminLogin'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'Index',
      redirect: '/user',
    },
    {
      path: '/login',
      name: 'Login',
      component: resolve => require(['@/components/Login'], resolve),
      meta: {
        title: '用户登录页面'
      }
    },
     {
      path: '/user',
      name: 'User',
      component: resolve => require(['@/components/User'], resolve),
      meta: {
        title: '用户页面',
        requireAuth: true
      }
    },
    {
      path: '/adminlogin',
      name: 'AdminLogin',
      component: resolve => require(['@/components/AdminLogin'], resolve),
      meta: {
        title: '管理员登录页面'
      }
    },
    {
      path: '/admin',
      name: 'Admin',
      component: resolve => require(['@/components/Admin'], resolve),
      meta: {
        title: '管理员页面',
        requireAdmin: true
      }
    }
  ]
})

export default router

router.beforeEach((to, from, next) => {
  // console.log(to)
  if (to.meta.title) {
    document.title = to.meta.title
  }
  if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
    if (sessionStorage.getItem("login") === 'true') {
      next()
    } else {
      next('/login')
    }
  } else if (to.meta.requireAdmin) { // 判断该路由是否需要登录权限
    if (sessionStorage.getItem("admin") === 'true') {
      next()
    } else {
      next('/adminlogin')
    }
  } else {
    next()
  }
})
